How do I use a sort key lambda in Python to sort a list? • GITNUX

您所在的位置:网站首页 python lambda sorted How do I use a sort key lambda in Python to sort a list? • GITNUX

How do I use a sort key lambda in Python to sort a list? • GITNUX

#How do I use a sort key lambda in Python to sort a list? • GITNUX| 来源: 网络整理| 查看: 265

Sorting lists in Python can be done using the `sorted()` function or the `sort()` method. Both of these functions accept a sort key lambda as an argument, which is a small anonymous function that helps to determine how elements should be sorted. This blog post will provide examples of how to use sort key lambdas with both the `sorted()` and `sort()` methods for sorting numbers and strings.

Programming Guide

In Python, you can use the `sorted()` function or the `sort()` method along with a sort key lambda to sort a list. The sort key lambda is a small anonymous function that you pass as an argument to help sort the list.

Here’s an example of how to use a sort key lambda to sort a list of numbers in descending order:

numbers = [4, 2, 9, 1, 7, 6] # Using the sorted function sorted_numbers = sorted(numbers, key=lambda x: -x) print(sorted_numbers) # Output: [9, 7, 6, 4, 2, 1] # Using the sort method numbers.sort(key=lambda x: -x) print(numbers) # Output: [9, 7, 6, 4, 2, 1]

Here’s another example of how to use a sort key lambda to sort a list of strings by their length:

words = ["apple", "banana", "cherry", "blueberry", "grape"] # Using the sorted function sorted_words = sorted(words, key=lambda x: len(x)) print(sorted_words) # Output: ['apple', 'grape', 'banana', 'cherry', 'blueberry'] # Using the sort method words.sort(key=lambda x: len(x)) print(words) # Output: ['apple', 'grape', 'banana', 'cherry', 'blueberry']

The `sort()` method sorts the list in-place and doesn’t return a new list. On the other hand, the `sorted()` function returns a new sorted list, preserving the order of the original list.

Conclusion

This blog post demonstrates how to use the `sorted()` function or the `sort()` method along with a sort key lambda to sort lists in Python. It provides two examples of sorting numbers and strings by their length, respectively. The main difference between these functions is that the `sort()` method sorts the list in-place while the `sorted()` function returns a new sorted list preserving the order of original one.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3